import 'dart:io';

import 'package:dio/dio.dart';

import '../config/env_config.dart';
import 'network_provider.dart';
import 'network_response.dart';

/// 网络请求类型
enum Method {
  get,
  post,
  put,
  head,
  delete,
  patch;

  String get rawValue => name.toUpperCase();
}

/// 网络请求目标
mixin TargetType {
  /// 详细路径
  ApiPath get path;

  /// 前缀（版本）
  String get prefix => "";

  /// 模块
  String get module => "";

  /// 请求方式
  Method get method;

  /// 基础链接
  String? get baseUrl => HMNetworkConfig.host.baseHost.current;

  /// 链接超时
  Duration? get connectTimeout => const Duration(seconds: 30);

  /// 接收超时
  Duration? get receiveTimeout => const Duration(seconds: 30);

  /// 发送超时
  Duration? get sendTimeout => const Duration(seconds: 30);

  /// 请求数据类型
  String get contentType => ContentType.json.mimeType;

  /// 响应数据类型
  ResponseType get responseType => ResponseType.json;

  /// 是否显示加载中
  bool get showLoading => true;

  /// 是否显示错误提示
  bool get showErrorToast => false;

  /// 本地mock数据
  MockData? get mockData => null;

  /// 暗黑模式？
  bool get isDark => false;

  /// 发起请求
  Future<ResponseResult<T>> request<T>({
    CancelToken? cancelToken,
    ProgressCallback? onReceiveProgress,
    ProgressCallback? onSendProgress,
    Map<String, dynamic>? queryParameters,
    dynamic data,
    Map<String, dynamic>? headers,
    TransformValue<T>? transformer,
  }) {
    return NetworkProvider.shared.request(
      this,
      cancelToken: cancelToken,
      onReceiveProgress: onReceiveProgress,
      onSendProgress: onSendProgress,
      queryParameters: queryParameters,
      data: data,
      headers: headers,
      transformer: transformer,
    );
  }

  /// 完整路径
  String fullPath() {
    var fullPath = "";
    final prefixPath = _trimString(prefix);
    final modulePath = _trimString(module);
    final detailPath = _trimString(path.path);
    if (prefixPath.isNotEmpty) {
      fullPath += "/$prefixPath";
    }
    if (modulePath.isNotEmpty) {
      fullPath += "/$modulePath";
    }
    if (detailPath.isNotEmpty) {
      fullPath += "/$detailPath";
    }
    return fullPath;
  }

  /// 去掉首尾空格和/
  String _trimString(String input) {
    String result = input.trim();
    if (result.startsWith('/')) {
      result = result.substring(1);
    }
    if (result.endsWith('/')) {
      result = result.substring(0, result.length - 1);
    }
    return result;
  }
}

/// 接口路径
class ApiPath {
  /// 详细路径
  final String path;

  /// 接口描述
  final String description;

  const ApiPath(
    this.path,
    this.description,
  );
}

/// mock数据
class MockData {
  int statusCode;
  dynamic data;
  Duration? delay;

  MockData._({
    required this.statusCode,
    required this.data,
    this.delay,
  });

  factory MockData({
    required int statusCode,
    required dynamic data,
    Duration? delay,
  }) {
    return MockData._(
      statusCode: statusCode,
      data: data,
      delay: delay,
    );
  }
}
